package com.example.dllo.keepdemo.dynamic.find;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.example.dllo.keepdemo.R;
import com.example.dllo.keepdemo.base.BaseFragment;
import com.example.dllo.keepdemo.dynamic.ExquisiteDynamicActivity;
import com.example.dllo.keepdemo.dynamic.bean.FindBannerBean;
import com.example.dllo.keepdemo.dynamic.bean.FindBean;
import com.example.dllo.keepdemo.dynamic.bean.FindHeadBean;
import com.example.dllo.keepdemo.greendao.DynamicFind;
import com.example.dllo.keepdemo.greendao.DynamicFindDao;
import com.example.dllo.keepdemo.tools.DaoSingleton;
import com.example.dllo.keepdemo.tools.GsonRequest;
import com.example.dllo.keepdemo.tools.HeaderGridView;
import com.example.dllo.keepdemo.tools.RecyclerViewOnClick;
import com.example.dllo.keepdemo.tools.RoundImageView;
import com.example.dllo.keepdemo.tools.VolleySingleton;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 16/1/8.
 */
public class FindFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private HeaderGridView headerGridView;
    private HeaderGridViewAdapter adapter;
    private LinearLayout linearLayout;
    public ViewPager viewPager;
    public ImageHandler handler;
    private FindBean findBean;
    private DynamicFindDao dynamicFindDao = DaoSingleton.getInstance().getDynamicFindDao();
    private RoundImageView roundImageView1,roundImageView2,roundImageView3,roundImageView4,roundImageView5,roundImageView6;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find, container, false);
        headerGridView = (HeaderGridView) view.findViewById(R.id.headergridview_fragment_find);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.header_gridview_fragment_find,null);
        linearLayout = (LinearLayout) view.findViewById(R.id.linear_header_headergridview_fragment_find_expert);
        viewPager = (ViewPager) view.findViewById(R.id.viewpager_header_fragment_find);
        roundImageView1 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_one);
        roundImageView2 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_two);
        roundImageView3 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_three);
        roundImageView4 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_four);
        roundImageView5 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_five);
        roundImageView6 = (RoundImageView) view.findViewById(R.id.roundimg_header_gridview_find_six);

        linearLayout.setOnClickListener(this);
        headerGridView.setOnItemClickListener(this);

        initData();

        headerGridView.addHeaderView(view);
        headerGridView.setNumColumns(2);
        handler = new ImageHandler(new WeakReference<FindFragment>(this));

        initImgData();

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                handler.sendMessage(Message.obtain(handler, ImageHandler.MSG_PAGE_CHANGED, position, 0));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        handler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                        break;
                    case ViewPager.SCROLL_STATE_IDLE:
                        handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                        break;
                    default:
                        break;
                }
            }
        });

        viewPager.setCurrentItem(ImageHandler.MSG_PAGE_CHANGED);//默认在中间，使用户看不到边界
        //开始轮播效果
        handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
        getScrollData();

    }

    private void initImgData() {
        String url = "https://api.gotokeep.com/v1.1/rankinglist/user/wall?limit=6";
        final RoundImageView[] imageViews = {roundImageView1, roundImageView2, roundImageView3, roundImageView4, roundImageView5, roundImageView6};
        GsonRequest<FindHeadBean> gsonRequest = new GsonRequest<FindHeadBean>(url, FindHeadBean.class, new Response.Listener<FindHeadBean>() {
            @Override
            public void onResponse(FindHeadBean response) {
                Log.d("FindFragment", "response:" + response);
                for (int i = 0; i < response.getData().size(); i++) {
                    if (response.getData().get(i).getAvatar().equals("") || !(response.getData().get(i).getAvatar().endsWith(".jpg"))) {
                        imageViews[i].setImageResource(R.mipmap.person_45_45);
                    } else {
                        ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageViews[i], R.mipmap.person_45_45, R.mipmap.person_45_45);
                        VolleySingleton.getImageLoader().get(response.getData().get(i).getAvatar(), listener, 60, 60);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("FindFragment", "shibai");
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<>();
                map.put("X-X", "c63345be44019b890c6e9b19a7e91deb1643af1b");
                map.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjViMWQxYjk4MDQwYTI5MDVlZjgwM2MiLCJ1c2VybmFtZSI6ImVnZ3Nzc3NzIiwiYXZhdGFyIjoiaHR0cDovL3EucWxvZ28uY24vcXFhcHAvMTEwMzcyNzQ0Ni9BRjI1QjEzQzNFNTYzQzIzRkZCQ0VEN0IwRENGQkQyQS8xMDAiLCJpYXQiOjE0NTMyODM2MDAsImV4cCI6MTQ1NTg3NTYwMCwiaXNzIjoiaHR0cDovL3d3dy5nb3Rva2VlcC5jb20vIn0.BQfDXNIAjc3GkyaNht5cr_c4eEC9j1i4n7weALTRqY4");
                map.put("Host", "api.gotokeep.com");
                return map;
            }
        };
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void getScrollData() {
        String url = "https://api.gotokeep.com/v1.1/banners";
        GsonRequest<FindBannerBean> gsonRequest = new GsonRequest<FindBannerBean>(url, FindBannerBean.class, new Response.Listener<FindBannerBean>() {
            @Override
            public void onResponse(FindBannerBean response) {
                List<ImageView> imageViewList = new ArrayList<>();
                for (int i = 0; i < response.getData().size(); i++) {
                    ImageView imageView = new ImageView(getActivity());
                    ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView,R.mipmap.plan320_160,R.mipmap.plan320_160);
                    VolleySingleton.getImageLoader().get(response.getData().get(i).getPhoto(),listener,400,200);
                    imageViewList.add(imageView);
                }
                viewPager.setAdapter(new ViewPagerAdapter(imageViewList));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String,String> map = new HashMap<>();
                map.put("X-X","c63345be44019b890c6e9b19a7e91deb1643af1b");
                map.put("Authorization","Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjViMWQxYjk4MDQwYTI5MDVlZjgwM2MiLCJ1c2VybmFtZSI6ImVnZ3Nzc3NzIiwiYXZhdGFyIjoiaHR0cDovL3EucWxvZ28uY24vcXFhcHAvMTEwMzcyNzQ0Ni9BRjI1QjEzQzNFNTYzQzIzRkZCQ0VEN0IwRENGQkQyQS8xMDAiLCJpYXQiOjE0NTMyODM2MDAsImV4cCI6MTQ1NTg3NTYwMCwiaXNzIjoiaHR0cDovL3d3dy5nb3Rva2VlcC5jb20vIn0.BQfDXNIAjc3GkyaNht5cr_c4eEC9j1i4n7weALTRqY4");
                map.put("Host","api.gotokeep.com");
                return map;
            }
        };

        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void initData() {
        findBean = new FindBean();
        String url = "https://api.gotokeep.com/v1.1/timeline/hot";
        GsonRequest<FindBean> gsonRequest = new GsonRequest<FindBean>(url, FindBean.class, new Response.Listener<FindBean>() {
            @Override
            public void onResponse(FindBean response) {
                findBean = response;
                adapter = new HeaderGridViewAdapter(getActivity(),findBean,2);
                headerGridView.setAdapter(adapter);

                if (null != dynamicFindDao.queryBuilder().list()) {
                    dynamicFindDao.deleteAll();
                    addData(response);
                } else {
                    addData(response);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                adapter = new HeaderGridViewAdapter(dynamicFindDao.queryBuilder().list(),getActivity(),1);
                headerGridView.setAdapter(adapter);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI1NjY1MDBlMTYzZGIwYzlmNTdiMTQwYWQiLCJ1c2VybmFtZSI6Iuaeq-WQmyIsImF2YXRhciI6Imh0dHA6Ly93eC5xbG9nby5jbi9tbW9wZW4vc2t3MmhSR3lXRWcwUzV0NzhkMlRVUnFhYjBzcWJ4RXB4S1BLUFpEOXpwbTNJbkIySzRjRnhLVEJsemdDb3VIcGlia3RkRUluQ0NFcGpIS2FHZ1lwRkp6SVRIVU5NYTNpYmYvMCIsImlhdCI6MTQ1MjU4OTkwNiwiZXhwIjoxNDU1MTgxOTA2LCJpc3MiOiJodHRwOi8vd3d3LmdvdG9rZWVwLmNvbS8ifQ.4I6FpbJT1_1fe8Z51oHt6Mv5t-3zXGGYhI1rMe3U8gM");
                map.put("X-X", "486bba2566a02d3ae31ed4445366a873b89cf910");
                map.put("Host", "api.gotokeep.com");
                map.put("X-KEEP-VERSION", "2.8.1");
                map.put("X-KEEP-CHANNEL", "keep");
                return map;
            }
        };

        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void addData(FindBean response) {
        List<DynamicFind> dynamicFindList = new ArrayList<>();
        for (int i = 0; i < response.getData().size(); i++) {
            DynamicFind dynamicFind = new DynamicFind();
            dynamicFind.setContent(response.getData().get(i).getContent());
            dynamicFind.setLikes(response.getData().get(i).getLikes() + "");
            dynamicFind.setComment(response.getData().get(i).getComments() + "");
            dynamicFind.setUrl(response.getData().get(i).getPhoto());
            dynamicFindList.add(dynamicFind);
        }
        dynamicFindDao.insertInTx(dynamicFindList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.linear_header_headergridview_fragment_find_expert :
                Toast.makeText(getActivity(), "社区达人", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        Toast.makeText(getActivity(), "position:" + (position - 2), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getActivity(), ExquisiteDynamicActivity.class);
        intent.putExtra("position",(position - 2));
        startActivity(intent);
    }
}
